package com.pignest.hotel.ui.income;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.beans.TbAccounts;
import com.pignest.hotel.beans.TbCloseAccounts;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.service.IncomeService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Global;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class PartCheckOutWindow extends Window implements EventListener {

	/**
	 * 部分结账
	 */
	private static final long serialVersionUID = 8298749738546428005L;

	private IncomeService incomeService;
	private MemberService memberService;
	
	private Label storage;
	private Label used;
	private Textbox available;//当前余额
	
	private Textbox accounts;//结账金额
	private Textbox payAcounts;//结算金额
	private Listbox paymentMethod;//结账类型
	private Listbox invoiceListbox;//是否开票

	private Textbox mCardNumber;//会员卡号
	
	private Textbox livingTime;//到达时间
	private Textbox leaveTime;//离开时间
	
	private Button okBtn;
	private Label opTip;
	
	public Living selLiving;//选择的入住
	public List<TbAccounts> selAccList;//选择部分结账记录
	private Grid memberGrid;
	
	public PartCheckOutWindow()
	{
		incomeService =Services.getIncomeService();
		memberService=Services.getMemberService();
		addEventListener("onCreate", this);
	}
	@Override
	public void onEvent(Event event) throws Exception {
		// TODO Auto-generated method stub
		if ("onCreate".equals(event.getName())) {
			storage =(Label)getFellow("storage");
			used =(Label)getFellow("used");
			livingTime=(Textbox)getFellow("livingTime");
			leaveTime=(Textbox)getFellow("leaveTime");
			available=(Textbox)getFellow("available");
			
			accounts=(Textbox)getFellow("accounts");
			payAcounts=(Textbox)getFellow("payAcounts");
			paymentMethod=(Listbox)getFellow("paymentMethod");
			invoiceListbox=(Listbox)getFellow("invoiceListbox");
	
			mCardNumber=(Textbox)getFellow("mCardNumber");
			
			opTip=(Label)getFellow("opTip");
			okBtn=(Button)getFellow("okBtn");
			memberGrid=(Grid)getFellow("memberGrid");
			memberGrid.setVisible(false);
		}
		init();
		paymentMethod.addEventListener(Events.ON_SELECT, new EventListener(){
			   public void onEvent(Event event) {
				   PayMethod payMethod=UIUtils.getSelectedValue(paymentMethod);
				   if(payMethod.name().equals(PayMethod.MEMBER_CARD.name()))
				   {
					   memberGrid.setVisible(true);
				   }else{
					   memberGrid.setVisible(false);
					   okBtn.setDisabled(false);
				   }
				   onChangeCheck();
				   
			   }
		   });
		
	}
	public void init()
	{
		rightLivingInfo(selLiving);
		leftAccountsInfo();
	}
	//初始化右边的信息
	public void rightLivingInfo(Living l)
	{
		if(l==null)
			return;
		livingTime.setValue(DateUtil.toString(l.getLiveTime(), DateUtil.HOTEL_DEFAULT_FORMAT));
		leaveTime.setValue(DateUtil.toString(l.getLeaveDate(), DateUtil.HOTEL_DEFAULT_FORMAT));
		available.setValue(MoneyUtil.toString(l.getAvailable()));
		storage.setValue(MoneyUtil.toString(l.getStorage()));
		used.setValue(MoneyUtil.toString(l.getUsed()));
	}
	//初始化左边信息
	public void leftAccountsInfo()
	{
	   if(selAccList==null)
		   return;
	   int iAccounts=0;
	   for(TbAccounts a:selAccList){
		   iAccounts=iAccounts-a.getPrice();
	   }
	   accounts.setValue(String.valueOf(MoneyUtil.randPositive(MoneyUtil.cent2dollar(iAccounts))));
	   payAcounts.setValue(Utils.toPrice(iAccounts));
	}
	//TODO 会员还没处理
	public void partCheck()
	{
		if(!Hotel.onDuty()){
			UIUtils.alert("你未值班不能操作此业务!");
			return ;
		}
		
		StringBuffer msg = new StringBuffer();
		msg.append("你好：").append(selLiving.getCustormName()).append("\n");
		PayMethod payMethod=UIUtils.getSelectedValue(paymentMethod);
		int invoice=Integer.valueOf((String)UIUtils.getSelectedValue(invoiceListbox));
		String iacc =accounts.getValue();
		String orderNo=DateUtil.toString(selLiving.getLiveTime(),"yyyyMMddHHmmss");

		int payfor =Utils.toPrice(payAcounts.getValue());
		//int payfor=MoneyUtil.dollar2cent(pay);
		if(iacc==null||iacc.equals("0")){
			UIUtils.alert("所结账的金额为0不需要结账!");
			return ;
		}
		int iAccounts=Utils.toPrice(iacc);
		Member m=null;
		Memberchargehistrory mch=null;
		TbAccounts account =null;
		
		if(payMethod.name().equals(PayMethod.MEMBER_CARD.name()))//如果是会员结账
		{
			String cardNo=mCardNumber.getValue();
		    m =memberService.queryMemberOnCard(cardNo);
		    if(m==null)
		    {
		    	UIUtils.alert("无效的会员卡!");
		    	return ;
		    }
		    int exceed=memberService.exceedBalance(m, iAccounts, false);
		    if(exceed<=0)
		    {
		    	UIUtils.alert("会员余额不足!");
		    	return ;
		    }
		  //增加会员消费记录
        	mch = new Memberchargehistrory();
			mch.setMember(m);
			mch.setChargeTime(new Date());
			mch.setPrice(-iAccounts);
			mch.setChargetype("非自助");
			mch.setOptype(ChargeOpType.OnConsume.name());
			mch.setRemark(selLiving.getCustormName()+":"+DateUtil.curDateStr()+ChargeOpType.OnCharge.getValue()+Utils.toPrice(iAccounts));
			//this.insert(mch);
        	//将扣会员存款
        	msg.append("结账方式：").append(payMethod.getDisplayName()).append("\n");
        	msg.append("会员名:").append(m.getName()).append("\n");
		}
		msg.append("结账方式：").append(payMethod.getDisplayName()).append("\n");
		msg.append("部分结账:").append(Utils.toPrice(iAccounts)).append("\n");
        if(payfor>iAccounts){
			msg.append("余额：").append(Utils.toPrice(payfor-iAccounts)).append("作为续款").append("\n");
			account =new TbAccounts();
			account.setLiving(selLiving);
			account.setType(InComeItemType.XCK.name());
			account.setCounts(1);
			account.setPrice(payfor-iAccounts);
			account.setPrice2(payfor-iAccounts);
			account.setName(InComeItemType.XCK.getName());
			account.setRemark("部分结账同时续费:"+Utils.toPrice(payfor-iAccounts));
			account.setState(TbAccounts.STATE_NORMAL);
			account.setEndstate("否");
			account.setOpdate(DateUtil.curDateStr());
			account.setOptime(new Date());
			account.setOpUser(Hotel.getCurrentUser().getName());
		}
		//
		TbCloseAccounts ca = new TbCloseAccounts();
		ca.setLiving(selLiving);
		ca.setInvoice(invoice);
		ca.setTime(new Date());
		ca.setAccounts(iAccounts);
		ca.setType(payMethod.name());
		User user =Hotel.getCurrentUser();
		ca.setUsername(user.getName());
		ca.setUserId(user.getId());
		ca.setOrderNo(orderNo);
		
		if(UIUtils.confirm(msg.toString())){
			incomeService.savePartCheckOut(selLiving, ca, selAccList, mch,account,payfor);
			opTip.setValue("操作成功！");
			okBtn.setDisabled(true);
		}
	}
	public Member query(String name,String cardNo)
	{
		return memberService.queryMemberOnCard(name, cardNo);
	}
	public void onChangeCheck()
	{
		if(!Utils.checkPrice(payAcounts.getValue())){
			UIUtils.alert("你输入的结算金额不对！请输入正数!");
			return ;
		}
		//Integer p =payAcounts.getValue();
		int p =Utils.toPrice(payAcounts.getValue());
		String a =accounts.getValue();
		//int iA =Integer.valueOf(a);
		int iA=Utils.toPrice(a);
		if(p<=0||p<iA)
		{
			opTip.setValue("结算金额不能小于结账金额！或者结算金额不能小等于0");
			okBtn.setDisabled(true);
		}else
		{
			int payCome =p-iA;
			if(payCome>0)
			{
				opTip.setValue("余额"+Utils.toPrice(payCome)+"将作为续存款！");
			}else
			{
				opTip.setValue("请继续你的操作！");
			}
			okBtn.setDisabled(false);
		}
		
		
	}
	public Living getSelLiving() {
		return selLiving;
	}
	public void setSelLiving(Living selLiving) {
		this.selLiving = selLiving;
	}
	public List<TbAccounts> getSelAccList() {
		return selAccList;
	}
	public void setSelAccList(List<TbAccounts> selAccList) {
		this.selAccList = selAccList;
	}
	

}
